package net.wzw.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author wzw
 * @date 2025/4/8
 * @Description
 */
@Slf4j
public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapperUtil();

    public static String object2Json(Object obj){

        if(obj == null){

            return  null;
        }
        String s = null;

        try {

            s = objectMapper.writeValueAsString(obj);

        }catch (Exception e)
        {

            log.warn("object to net.wzw.common.json.json error",e);
        }

        return s;
    }

    /*
     * Description: Json字符串转指定类型的对象
     * @param null
     * @Return: {@link null}
     * @Author: Administrator
     * @Date: 2025/4/9 16:41
     */
     public static<T> T json2Object(String json,Class<T> clazz){

         if(!StringUtils.hasLength(json)){

             return null;
         }

         try {

             return  objectMapper.readValue(json,clazz);

         }catch (Exception e)
         {
             log.warn("net.wzw.common.json to object error ",e);
         }

          return  null;
     }

     /*
      * Description: json转list
      * @param null
      * @Return: {@link null}
      * @Author: Administrator
      * @Date: 2025/4/20 1:43
      */
    public static <T> List<T> StringtoList(String json,Class<T> clazz) {

        try {
            return objectMapper.readValue(json, new TypeReference<List<T>>() {
            });
        } catch (JsonMappingException e)
        {
            throw  new RuntimeException( e);

        }catch (JsonProcessingException e){

            throw new RuntimeException(e);

        }


    }

    /**
     * json 转 list<Long>
     * **/
    public static List<Long> jsonToLongList(String json){

        List<Long> result = new ArrayList<>();
        List<Map<String,String>> mapList = null;

        try {
            mapList =  objectMapper.readValue(json, new TypeReference<List<Map<String,String>>>() {
            });
        }catch (JsonProcessingException e)
        {

            throw new RuntimeException(e);

        }
        for (Map<String,String> map : mapList){

            for (Map.Entry<String,String> entry : map.entrySet()){

                result.add(Long.parseLong(entry.getValue()));
            }

        }
        return result;

    }


}
